package com.itheima.reggie.filter;

import com.alibaba.fastjson.JSON;
import com.itheima.reggie.common.BaseContext;
import com.itheima.reggie.common.R;
import com.itheima.reggie.entity.Employee;
import com.itheima.reggie.entity.User;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.AntPathMatcher;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/*
    登录过滤器：未登录跳转到login.html
 */
@WebFilter("/*")
@Slf4j
public class LoginCheckFilter implements Filter {
    private static final AntPathMatcher PATH_MATCHER = new AntPathMatcher();

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        log.info("LoginCheckFilter类中此时的线程id为：{}", Thread.currentThread().getId());
        //1.获取本次请求的URI
        HttpServletRequest req = (HttpServletRequest) servletRequest;
        HttpServletResponse resp = (HttpServletResponse) servletResponse;
        String uri = req.getRequestURI();//  /backend/index.html
        //2.判断本次访问URI是否需要直接放行
        //定义不需要处理的请求路径
        String[] urls = new String[]{
                "/employee/login",
                "/employee/logout",
                "/backend/**",
                "/front/**",
                "/user/sendMsg",
                "/user/login"
        };
        boolean flag = check(urls, uri);
        if (flag) {
            filterChain.doFilter(req, resp);
            return;
        }
        //3.判断本次请求的用户是否已经登录过
        Employee emp = (Employee) req.getSession().getAttribute("employee");
        if(emp!=null){
            //说明已经登录过了，要放行
            BaseContext.set(emp.getId());
            filterChain.doFilter(req,resp);//controller metaObject
            BaseContext.remove();
            return;
        }
        //4.判断如果用户的手机端，登录之后，也应该放行
        User user = (User) req.getSession().getAttribute("user");
        if(user!=null){
            BaseContext.set(user.getId());
            filterChain.doFilter(servletRequest, servletResponse);
            BaseContext.remove();
            return;
        }


        //5.没有登录过，跳转到登录页面(此时是异步访问)
        R r = R.error("NOTLOGIN");
        String json = JSON.toJSONString(r);
        resp.getWriter().write(json);
    }

    /*
        返回true：当前访问的路径在需要放行的路径数组中，放行
     */
    public boolean check(String[] urls, String uri) {
        for (String url : urls) {
            if (PATH_MATCHER.match(url, uri)) {
                return true;
            }
        }
        return false;//循环比较完毕之后，还没有返回true说明此时访问的路径，必须登录之后才能访问
    }

}
